from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.core.security import get_current_user
from app.schemas.wallet import WalletCreate, WalletUpdate, WalletInDB
from app.crud import wallet as wallet_crud
from app.db.session import get_db
from app.utils.response import Response
from app.core.exceptions import NotFoundError

router = APIRouter()

@router.post("/", response_model=WalletInDB)
async def create_wallet(
    *,
    db: Session = Depends(get_db),
    wallet_in: WalletCreate,
    current_user_id: int = Depends(get_current_user)
):
    """
    创建新钱包
    """
    try:
        wallet = wallet_crud.create_wallet(db, wallet_in, current_user_id)
        return Response.success(
            data=wallet,
            message="钱包创建成功"
        )
    except Exception as e:
        return Response.error(
            message=f"创建钱包失败: {str(e)}",
            error_code="CREATE_WALLET_ERROR"
        )

@router.get("/", response_model=List[WalletInDB])
async def get_wallets(
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user),
    skip: int = 0,
    limit: int = 100
):
    """
    获取当前用户的所有钱包
    """
    wallets = wallet_crud.get_user_wallets(db, current_user_id, skip=skip, limit=limit)
    return Response.success(data=wallets)

@router.get("/{wallet_id}", response_model=WalletInDB)
async def get_wallet(
    *,
    db: Session = Depends(get_db),
    wallet_id: int,
    current_user_id: int = Depends(get_current_user)
):
    """
    获取指定钱包详情
    """
    wallet = wallet_crud.get_wallet(db, wallet_id)
    if not wallet or wallet.user_id != current_user_id:
        raise NotFoundError(detail="钱包不存在")
    return Response.success(data=wallet)

@router.put("/{wallet_id}", response_model=WalletInDB)
async def update_wallet(
    *,
    db: Session = Depends(get_db),
    wallet_id: int,
    wallet_in: WalletUpdate,
    current_user_id: int = Depends(get_current_user)
):
    """
    更新钱包信息
    """
    wallet = wallet_crud.get_wallet(db, wallet_id)
    if not wallet or wallet.user_id != current_user_id:
        raise NotFoundError(detail="钱包不存在")
    
    wallet = wallet_crud.update_wallet(db, wallet_id, wallet_in)
    return Response.success(
        data=wallet,
        message="钱包更新成功"
    )

@router.delete("/{wallet_id}")
async def delete_wallet(
    *,
    db: Session = Depends(get_db),
    wallet_id: int,
    current_user_id: int = Depends(get_current_user)
):
    """
    删除钱包
    """
    wallet = wallet_crud.get_wallet(db, wallet_id)
    if not wallet or wallet.user_id != current_user_id:
        raise NotFoundError(detail="钱包不存在")
    
    wallet_crud.delete_wallet(db, wallet_id)
    return Response.success(message="钱包删除成功") 